const fs = require('fs');
const path = require('path');
const JavaScriptObfuscator = require('javascript-obfuscator');

// 需要混淆的文件列表
const filesToObfuscate = [
  'content.js',
  'background.js',
  'sidebar.js'
];

// 混淆配置
const obfuscationOptions = {
  compact: true,
  controlFlowFlattening: true,
  controlFlowFlatteningThreshold: 0.5,  // 降低控制流扁平化的阈值
  deadCodeInjection: false,  // 禁用死代码注入
  debugProtection: false,    // 禁用调试保护
  debugProtectionInterval: false,
  disableConsoleOutput: false,
  identifierNamesGenerator: 'hexadecimal',
  log: false,
  renameGlobals: false,
  rotateStringArray: true,
  selfDefending: false,      // 禁用自我保护
  shuffleStringArray: true,
  splitStrings: true,
  splitStringsChunkLength: 10,
  debugProtectionInterval: 2000,  // 修改这里，设置一个具体的数值（毫秒）
  stringArray: true,

  stringArrayEncoding: ['rc4', 'base64'],  // 使用双重编码
  stringArrayThreshold: 0.75,
  transformObjectKeys: false, // 禁用对象键转换
  unicodeEscapeSequence: true,
  reservedNames: ['chrome'],  // 保留 chrome 关键字不被混淆
  reservedStrings: ['chrome\\..*'], // 保留所有 chrome.* API 调用
};

// 创建输出目录
const outputDir = path.join(__dirname, 'dist');
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir);
}

// 混淆文件
filesToObfuscate.forEach(file => {
  const filePath = path.join(__dirname, file);
  const outputPath = path.join(outputDir, file);
  
  if (fs.existsSync(filePath)) {
    const code = fs.readFileSync(filePath, 'utf8');
    const obfuscatedCode = JavaScriptObfuscator.obfuscate(code, obfuscationOptions).getObfuscatedCode();
    fs.writeFileSync(outputPath, obfuscatedCode);
    console.log(`已混淆文件: ${file}`);
  } else {
    console.error(`文件不存在: ${file}`);
  }
});

// 复制其他必要文件
const filesToCopy = [
  'manifest.json',
  'sidebar.html',
  'assets'
];

filesToCopy.forEach(item => {
  const sourcePath = path.join(__dirname, item);
  const targetPath = path.join(outputDir, item);
  
  if (fs.existsSync(sourcePath)) {
    if (fs.lstatSync(sourcePath).isDirectory()) {
      // 递归复制目录
      copyFolderRecursiveSync(sourcePath, outputDir);
    } else {
      // 复制文件
      fs.copyFileSync(sourcePath, targetPath);
    }
    console.log(`已复制: ${item}`);
  } else {
    console.error(`文件或目录不存在: ${item}`);
  }
});

// 递归复制目录函数
function copyFolderRecursiveSync(source, target) {
  const targetFolder = path.join(target, path.basename(source));
  if (!fs.existsSync(targetFolder)) {
    fs.mkdirSync(targetFolder, { recursive: true });
  }

  if (fs.lstatSync(source).isDirectory()) {
    const files = fs.readdirSync(source);
    files.forEach(file => {
      const curSource = path.join(source, file);
      if (fs.lstatSync(curSource).isDirectory()) {
        copyFolderRecursiveSync(curSource, targetFolder);
      } else {
        fs.copyFileSync(curSource, path.join(targetFolder, file));
      }
    });
  }
}

console.log('构建完成！');